<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../extjs_all/resources/css/ext-all.css"></link>
<script type="text/javascript" src="../../extjs_all/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../../extjs_all/ext-all.js"></script>
<script type="text/javascript" src="../../extjs_all/source/locale/ext-lang-zh_CN.js"></script>
<script type="text/javascript" src="../../myext/myVtype.js"></script>
<!-- script type="text/javascript" src="../myext/PersonListGridPanel.js"></script> -->
<script type="text/javascript">
	Ext.onReady(function(){
		Ext.QuickTips.init();	//初始化Ext.QuickTips，以使得tip提示可用
		Ext.form.Field.prototype.msgTarget='side';		//提示后面显示图片标记
		
		/**
		 * JS中，当有对象需要引用的时候，必须在引用之前就定义，否则的话，需要在constructor中初始化
		 */
		UserEnterInfoFormPanel = Ext.extend(Ext.form.FormPanel,{
			constructor:function(){
				UserEnterInfoFormPanel.superclass.constructor.call(this,{
					layout:'column',
					defaults:{anchor:'90%'},		//自动拉伸
					baseCls:'x-plain',			//强制设置窗体颜色
					defaultType:'textfield',
					bodyStyle:'padding:8px',
					
					items:[{
						
						xtype:'panel',				//上面指定为textfield后，items在此处声明xtype:'panel'，此时控件类型为panel
					    layout:'column',
					    baseCls:'x-plain',			//使内部的样式跟外面一样
					    //style:'padding:5px',
					    items:[{
					    		width:640,
					    		columnWidth:.5,
					    		layout:'form',
					    		defaultType:'textfield',	//指定itmes内所有的控件类型都为：textfield
					    		defaults:{width:230},
					    		labelWidth:70,
					    		baseCls:'x-plain',			//使内部的样式跟外面一样
					    		items:[{
									xtype:'hidden',
									name:'id'
									},{
					    				fieldLabel:'姓 名',
										allowBlank:false,
										name:'username',
										vtype:'enChNum',
										maxLength:50
					    			},{
					    				fieldLabel:'工 号',
										allowBlank:false,
										name:'userId',
										vtype:'enNumbers',
										maxLength:50
					    			},{
					    				fieldLabel:'年 龄',
										xtype:'numberfield',
										allowBlank:false,
										vtype:'age',
										name:'age'
					    			},{
					    				fieldLabel:'身份证',
					    				allowBlank:false,
					    				vtype:'idcard',
										name:'cardId'
					    			},{
					    				fieldLabel:'民 族',
					    				name:'nationality',
					    				maxLength:20
					    			},{
						    			fieldLabel:'职 务',
						    			name:'post',
										maxLength:20
						    		},{
						    			fieldLabel:'工段/班组',
						    			name:'item',
										maxLength:20
						    		},{
					    				fieldLabel:'政治面貌',
										name:'politicsStatus',
										maxLength:20
				    				},{
				    					fieldLabel:'婚 否',
				    					xtype:'combo',
					    				mode:'local',
					    				displayField:'val',
					    				readOnly:true,
					    				triggerAction:'all',
					    				value:'否',
					    				name:'hasMerry',
					    				store:new Ext.data.SimpleStore({
					    					fields:['val'],
					    					data:[['是'],['否']]
					    				})
				    				},{
					    				xtype:'datefield',
					    				format:'Y-m-d',
					    				readOnly:true,
					    				allowBlank:false,
					    				fieldLabel:'入公司时间',
					    				value:new Date(),
					    				name:'employmentDate'
					    			},{
					    				fieldLabel:'部 门',
					    				xtype:'combo',
					    				name:'deptId',
					    				mode:'local',
					    				displayField:'sex',
					    				readOnly:true,
					    				triggerAction:'all',
					    				value:'男',
					    				store:new Ext.data.SimpleStore({
					    					fields:['sex'],
					    					data:[['男'],['女']]
					    				})
						    		}]
					    	},{
					    		width:640,
					    		columnWidth:.5,
					    		layout:'form',
					    		defaultType:'textfield',	//指定itmes内所有的控件类型都为：textfield
					    		defaults:{width:200},
					    		labelWidth:80,
					    		//columnWidth:.5,
					    		//layout:'form',
					    		//labelWidth:60,
					    		baseCls:'x-plain',			//使内部的样式跟外面一样
					    		items:[{
					    			xtype:'textfield',		//指定类型为textfield，但是通过inputType转换成image控件
					    			fieldLabel:'个人照片',
					    			width:170,
					    			height:170,
					    			inputType:'image'
					    		},{
			    					fieldLabel:'毕业院校',
									name:'school',
									maxLength:20
			    				},{
			    					fieldLabel:'学 历',
									name:'education',
									maxLength:20
			    				},{
			    					fieldLabel:'专 业',
									name:'professionType',
									maxLength:500
			    				},{
			    					fieldLabel:'专业技术职务',
									name:'professionTypeName',
									maxLength:500
			    				}]
					    	}]
					},{
						xtype:'panel',				//上面指定为textfield后，items在此处声明xtype:'panel'，此时控件类型为panel
					    layout:'column',
					    baseCls:'x-plain',			//使内部的样式跟外面一样
					    items:[{
					    		width:660,
					            xtype:'fieldset',
					           /// title: '员工工资信息登记',
					            collapsible: false,
					           autoHeight:true,
					            bodyStyle:'padding:8px',
					            defaults: {},
					            defaultType: 'textfield',
					            items :[{
									
									xtype:'panel',				//上面指定为textfield后，items在此处声明xtype:'panel'，此时控件类型为panel
								    layout:'column',
								    baseCls:'x-plain',			//使内部的样式跟外面一样
								    //style:'padding:5px',
								    items:[{
								    		width:640,
								    		columnWidth:.5,
								    		layout:'form',
								    		defaultType:'textfield',	//指定itmes内所有的控件类型都为：textfield
								    		defaults:{width:230},
								    		labelWidth:60,
								    		baseCls:'x-plain',			//使内部的样式跟外面一样
								    		items:[{
													xtype:'hidden',
													name:'salaryId'
												},{
								    				fieldLabel:'工资标准',
								    				xtype:'numberfield',
													allowBlank:false,
													name:'basicSalary',
								    			},{
								    				fieldLabel:'工资卡号',
													allowBlank:false,
													name:'salaryCardNum',
													maxLength:100
								    			},{
								    				fieldLabel:'就职状态',
													allowBlank:false,
													maxLength:20,
													name:'jobState'
								    			},{
													xtype:'datefield',
								    				format:'Y-m-d',
								    				readOnly:true,
								    				fieldLabel:'离职时间',
								    				name:'leaveDate'
								    			},{
								    				fieldLabel:'离职原因',
								    				name:'leaveDesc',
								    				maxLength:2000
								    			}]
								    	},{
								    		width:640,
								    		columnWidth:.5,
								    		layout:'form',
								    		defaultType:'textfield',	//指定itmes内所有的控件类型都为：textfield
								    		defaults:{width:200},
								    		labelWidth:80,
								    		baseCls:'x-plain',			//使内部的样式跟外面一样
								    		items:[{
								    			fieldLabel:'社保类别',
												name:'sbtype',
												maxLength:50
								    		},{
						    					fieldLabel:'社保编号',
						    					vtype:'enNumbers',
						    					//xtype:'numberfield',
												name:'sbnum',
												maxLength:50
						    				},{
						    					fieldLabel:'医保编号',
						    					vtype:'enNumbers',
						    					//xtype:'numberfield',
												name:'ybnum',
												maxLength:50
						    				},{
						    					fieldLabel:'公积金编号',
						    					vtype:'enNumbers',
						    					//xtype:'numberfield',
												name:'gjjnum',
												maxLength:50
						    				},{
						    					fieldLabel:'失业保险',
												name:'synum',
												maxLength:50
						    				}]
								    	}]
								}]
					    }]
					}]
				})
			},
			getValues:function(){
				//alert(Ext.util.JSON.encode(this.form.getValues()));
				if(this.getForm().isValid()){
					this.fireEvent("submit",this,this.form.getValues());
				}else{
					throw Error("表单验证未通过！");		//抛出异常，在调用getValues函数的地方捕获并提示
				}
				//alert(this.getForm().getValues());
				return new Ext.data.Record(this.getForm().getValues());
			},
			setValues:function(re,detialrs){
				this.getForm().loadRecord(re);
				this.getForm().loadRecord(detialrs);
			},
			reset:function(){
				this.getForm().reset();
			}
		});
		/**
		 * 弹出编辑窗口类，提供创建和修改使用
		 */
		 UserEnterInfoWindow = Ext.extend(Ext.Window,{
			//将FormPanel放到Window中
			form:null,
			constructor:function(){
				this.form = new UserEnterInfoFormPanel(),
				UserEnterInfoWindow.superclass.constructor.call(this,{
					plain:true,			//通过背景颜色来渲染窗口颜色
					width:670,
					//resizable :false,
					modal:true,			//只能操作当前窗口
					closeAction:'hide',
					items:this.form,
					buttons:[{
							text:'确定',
							handler:this.onsubmit,
							scope:this
						},{
							text:'取消',
							handler:this.oncanel,
							scope:this
						}]
				});
				this.addEvents("submit");
			},	
			close:function(){
				this.form.reset();
				this.hide();
			},
			onsubmit:function(){
				try{
					this.fireEvent("submit",this,this.form.getValues());
					//获得Form提交后的ID,如果为空,表示添加,否则为修改
 					var id = Ext.util.JSON.encode(this.form.getValues().data.id);
					Ext.Ajax.request({
						url:'adduserenters.action',
						params:{
							content:"["+Ext.util.JSON.encode(this.form.getValues().data)+"]"
						},
						//提交成功后,处理一些事务
						 success : function(response){
						//	alert(response.responseText);
							var value = Ext.util.JSON.decode(response.responseText);
							var cc =new Ext.data.Record.create(['id','userId','username','age','cardId','nationality','deptId','item','post','employmentDate','politicsStatus','hasMerry','education','school','professionType','professionTypeName','photo']);
							var cdata = new cc(value.userEnter);
							//将数据插入到第一行,并删除store最后一行
							var gridStore = Ext.getCmp('userEnterGrid').store;
							var c = id.replace('"','').replace('"','');		//去除不必要的符号
							if(""==c){
								if(gridStore.getCount() == 20){
									gridStore.insert(0,cdata);
									gridStore.remove(gridStore.getAt(gridStore.getCount()-1));
								}else{
									//gridStore.add(cdata);
									gridStore.insert(0,cdata);
								}
							}else{
								var selectRe = Ext.getCmp('userEnterGrid').getSelectionModel().getSelected();			//获得Grid选择的record
								var data = selectRe.data;
								//alert(Ext.util.JSON.encode(data));		//获得Record的数据，然后转换成JSON打印
								//遍历record.data,修改原record的值
								for(var i in data){
									selectRe.set(i,cdata.get(i));
								}
								selectRe.commit();
								//同步详情表中的数据
								var usdata = new cc(value.userSalaryInfo);
								var detialRe =  Ext.getCmp('userEnterGridDetial').store.getAt(0);
								for(var i in detialRe.data){
									detialRe.set(i,usdata.get(i));
								}
								detialRe.commit();
							}
							Ext.Msg.alert('提示','操作成功!');
						}  
					});
				}catch(err){
					Ext.Msg.alert('提示',err);
					return ;
				}
				this.close();
			},
			oncanel:function(){
				this.close();
			}
		}) ;

		/*********************************/
		//添加
		InsertUserEnterInfoWindow = Ext.extend(UserEnterInfoWindow,{
			title:'添加员工信息'
		});
		//修改
		UpdateUserEnterInfoWindow = Ext.extend(UserEnterInfoWindow,{
			title:'修改员工信息',
			load:function(re,detialRs){
				//alert(Ext.util.JSON.encode(re.data))
			//	alert(Ext.util.JSON.encode(re.data.employmentDate.split('T')[0]))
				//格式化数据,让其正常显示
				re.data.employmentDate=re.data.employmentDate.split('T')[0];
				if(null != detialRs.data.leaveDate){
					detialRs.data.leaveDate = detialRs.data.leaveDate.split('T')[0];
				}
				this.form.setValues(re,detialRs);
			}
		});
		/**
		 * 员工信息显示Grid
		 */
		UserEnterGrid = Ext.extend(Ext.grid.GridPanel,{
			insertUserEnterWin:new InsertUserEnterInfoWindow(),
			updateUserEnterWin:new UpdateUserEnterInfoWindow(),
			constructor:function(){
				this['store']= new Ext.data.JsonStore({
					root:'list',
					totalProperty:'cnt',
					url:'finduserEnter.action',
				fields:[{
							name:'id', type: 'int'
						},{
							name:'age', type: 'int'
						},'userId','username','cardId','nationality','deptId','deptName','item','post',
						'employmentDate','politicsStatus','hasMerry','education','school','professionType','professionTypeName']
				}),
				//ToolBar
				this['toolBar'] = new Ext.Toolbar({
					
					items:[{
						text:'新增',
						icon:'../imgs/add.gif',
						cls: "x-btn-text-icon" ,		//自定义图片
						handler:function(){
							this.insertUserEnterWin.show();
						},
						scope:this
					},"-",{
						text:'修改',
						icon:'../imgs/edit.gif',
						cls: "x-btn-text-icon" ,		//自定义图片
						handler:function(){
							this.updateUserEnterWin.show();						//首先,修改窗体显示
							try{											//然后将用户选择的数据回写到窗体上	
							//	alert(123);
								var detialRs = Ext.getCmp('userEnterGridDetial').getStore().getAt(0);
							//alert(Ext.util.JSON.encode(detialRs.data));

								this.updateUserEnterWin.load(this.getSelected(),detialRs);
							}catch(err){
								Ext.Msg.alert('提示',err.description);
								this.updateUserEnterWin.close();
							}
						},
						scope:this
					},"-",{
						text:'删除',
						icon:'../imgs/delete.gif',
						cls: "x-btn-text-icon" ,		//自定义图片
// 						handler:function(){
// 							this.onRemove
// 							Ext.Msg.confirm('提示','是否删除？',this.onRemove,this);
// 						},
						handler:function(){
							this.onRemove()	
						},
						scope:this
					}]
				})
				UserEnterGrid.superclass.constructor.call(this,{
					id:'userEnterGrid',
					title:'员工信息列表',
					renderTo:'userEnterGrid',
					height:600,
					autoExpandColumn:13,
					//height : Ext.get('userEnterGrid').getHeight(), 
					tbar:this.toolBar,
					bbar:new Ext.PagingToolbar({
						pageSize:20,
						store:this.store,
						displayInfo:true,
						displayMsg:'第{0}条到{1}条，共{2}条',
						emptyMsg:'没有记录'
					}),
					columns:[
					         //new Ext.grid.RowNumberer(),//自动行号
								{
									header:'工号',
									width:100,
									dataIndex:'userId',
									sortable:true
								},{
									header:'姓名',
									width:100,
									dataIndex:'username',
									sortable:true
								},{
									header:'年龄',
									width:100,
									dataIndex:'age',
									sortable:true
								},{
									header:'身份证',
									width:200,
									dataIndex:'cardId',
									sortable:true
								},{
									header:'民族',
									width:100,
									dataIndex:'nationality',
									sortable:true
								},{
									header:'部门',
									width:100,
									dataIndex:'deptId',
									sortable:true
								},{
									header:'工段/班组',
									width:100,
									dataIndex:'item',
									sortable:true
								},{
									header:'职务',
									width:100,
									dataIndex:'post',
									sortable:true
								},{
									header:'入公司时间',
									width:100,
									dataIndex:'employmentDate',
									renderer:function(val){
										if(val!=null)
										 return val.split('T')[0]
									},
										
									sortable:true
								},{
									header:'政治面貌',
									width:100,
									dataIndex:'politicsStatus',
									sortable:true
								},{
									header:'婚否',
									width:100,
									dataIndex:'hasMerry',
									sortable:true
								},{
									header:'毕业院校',
									width:100,
									dataIndex:'school',
									sortable:true
								},{
									header:'学历',
									width:100,
									dataIndex:'education',
									sortable:true
								},{
									header:'专业',
									dataIndex:'professionType',
									sortable:true
								}],
					selModel:new Ext.grid.RowSelectionModel({
						singleSelect:true,
						listeners:{
							'rowselect':{
								fn:function( rowselectmodel,  rowIndex,r)	{
// 									this.fireEvent("rowselect",rowselectmodel,rowIndex,r)
									this.fireEvent("rowselect", r)
									//添加GridPanel的rowselect事件，此处的addEvents('rowselect')要与this.fireEvent("rowselect",r)的名称相同，
									//在调用的时候使用：UserEnterGrid().on( 'rowselect', function(){});那么就会调用。跟原始的直接写法是同样的效果
								},
								scope:this
							}
						}
					})
				});
				this.addEvents('rowselect');	
				this.getStore().load({
					url:'finddatas.action',
					params:{start:0,limit:20}
				});
				//this.insertDataDict.on('submit',this.onsubmit,this);		//为可视化窗口:insertWin添加事件(事件名称，调用的函数，scope)
			Ext.Ajax.on('requestcomplete',this.requestFunction,this);
		},
		//判断用户是否选择了数据
		getSelected:function(){
			var sm = this.getSelectionModel();
			if(sm.getCount() == 0){
				throw Error('需要选择一条数据');
			}
			return sm.getSelected();	
			
		},
		//删除数据
		onRemove:function(){
			var sm = this.getSelectionModel();
			if(sm.getCount() == 0){
				Ext.Msg.alert('提示','需要选择一条数据');
			}else{
				Ext.Msg.confirm('提示','是否删除？',function(btn, text){
					//Ext.Msg.confirm('提示','是否删除？',this.onRemove,this);
					if(btn == 'yes'){
						try{
							var store = this.store;
							var selectRe = this.getSelected();			//获得Grid选择的record
							
							store.remove(selectRe);
							
							Ext.Ajax.request({
								url:'deluserenters.action',
								params:{
									'userEnter.id':selectRe.get('id'),
									'userSalaryInfo.userEnterId':selectRe.get('id')
								},
								success : function(response){
									//alert(response.responseText);
									store.load({
											params:{start:0,limit:20}
										});
									Ext.getCmp('userEnterGridDetial').store.removeAll();
								}  
								
							});	//修改时，form联动
						}catch(err){
							Ext.Msg.alert('提示','需要选择一条数据');
						}
						//删除后,直接刷新
						
					}
				},this);
			}
		},
		//在插入数据的时候,返回的ID需要重新加载到insertdata对象中,这样就同数据库一样了,根据ID可以修改和删除数据
		requestFunction:function(conn,response,options){
// 			var c = Ext.util.JSON.decode(response.responseText);
// 			alert(response.responseText.cnt)
// 			var res = c.list;
// 			for(var i = 0;i<res.length;i++){
// 				var rc = res[i];
// 			}
		}
		});
		/**
		 * 员工基本信息详情
		 */
		UserEnterDetialGrid = Ext.extend(Ext.grid.GridPanel,{
			insertUserEnterWin:new InsertUserEnterInfoWindow(),
			updateUserEnterWin:new UpdateUserEnterInfoWindow(),
			constructor:function(){
				this['store']= new Ext.data.JsonStore({
					//data:[],

				fields:[{
							name:'id', type: 'int'
						},{
							name:'itemId', type: 'int'
						},'dictName','value1','value2','remark','parentId']
				}),
				
				UserEnterDetialGrid.superclass.constructor.call(this,{
					id:'userEnterGridDetial',
					title:'员工信息详情',
					renderTo:'userEnterGridDetial',
					height:200,
					autoExpandColumn:9,
					//height : Ext.get('userEnterGridDetial').getHeight(), 
					sm:new Ext.grid.RowSelectionModel({
						singleSelect:true
					}),
					tbar:this.toolBar,
					store:this.store,
					columns:[
					         //new Ext.grid.RowNumberer(),//自动行号
					
								{
									header:'工资标准',
									width:100,
									dataIndex:'basicSalary',
									sortable:true
								},{
									header:'工资卡号',
									width:200,
									dataIndex:'salaryCardNum',
									sortable:true
								},{
									header:'就职状态',
									width:100,
									dataIndex:'jobState',
									sortable:true
								},{
									header:'社保类别',
									width:100,
									dataIndex:'sbtype',
									sortable:true
								},{
									header:'社保个人编号',
									width:200,
									dataIndex:'sbnum',
									sortable:true
								},{
									header:'医保个人编号',
									width:200,
									dataIndex:'ybnum',
									sortable:true
								},{
									header:'公积金个人编号',
									width:200,
									dataIndex:'gjjnum',
									sortable:true
								},{
									header:'失业保险',
									width:200,
									dataIndex:'synum',
									sortable:true
								},{
									header:'离职时间',
									width:100,
									dataIndex:'leaveDate',
									renderer:function(val){
										if(val!=null)
										 return val.split('T')[0]
									},
									sortable:true
								},{
									header:'离职原因',
									width:100,
									dataIndex:'leaveDesc',
									sortable:true
								}]
				});
				//this.insertDataDict.on('submit',this.onsubmit,this);		//为可视化窗口:insertWin添加事件(事件名称，调用的函数，scope)
			Ext.Ajax.on('requestcomplete',this.requestFunction,this);
		},
		//在插入数据的时候,返回的ID需要重新加载到insertdata对象中,这样就同数据库一样了,根据ID可以修改和删除数据
		requestFunction:function(conn,response,options){
// 			var c = Ext.util.JSON.decode(response.responseText);
// 			alert(response.responseText)
// 			var res = c.list;
// 			for(var i = 0;i<res.length;i++){
// 				var rc = res[i];
// 			}
		}
		});
		var userenterGrid = new UserEnterGrid();

		var detial = new UserEnterDetialGrid();
		userenterGrid.on('rowselect',function(re){
			//form_panel.setValues(re);
			//alert(Ext.util.JSON.encode(re.data.id));
			Ext.Ajax.request({
				url:'showuserdetial.action',
				params:{
					'userEnter.userId':Ext.util.JSON.encode(re.data.id)
				},
				success : function(response){
					//alert(response.responseText);
					var value = Ext.util.JSON.decode(response.responseText);
					var cc =new Ext.data.Record.create(['salaryId','userEnterId','basicSalary','salaryCardNum','jobState','leaveDate','leaveDesc','sbtype','sbnum','ybnum','gjjnum','synum']);
					var cdata = new cc(value.userSalaryInfo);
					//将数据插入到第一行,并删除store最后一行
					var gridStore = detial.store;
					gridStore.removeAll();
					gridStore.insert(0,cdata);
				}  
				
			})	//修改时，form联动
		});
	});
</script>
<title>员工基本信息列表</title>
</head>
<body>
<div id="userEnterGrid"  style="width:100%; height:100%" ></div>
<div id="userEnterGridDetial"  style="width:100%; height:100%" ></div>
</body>
</html>